Log Requests with Custom Middleware


Implement custom middleware to log incoming requests, helping in tracking and analyzing application traffic and performance. Use Artisan command to create a new middleware class.

php artisan make:middleware LogRequestsMiddleware

Modify the handle method within the generated middleware class (LogRequestsMiddleware.php) to log incoming requests.

// app/Http/Middleware/LogRequestsMiddleware.php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Log;

class LogRequestsMiddleware
{
    public function handle($request, Closure $next)
    {
        Log::info('New request: ' . $request->fullUrl());

        return $next($request);
    }
}

Register your custom middleware in the HTTP kernel (app/Http/Kernel.php).

// app/Http/Kernel.php

protected $routeMiddleware = [
    // Other middleware entries...
    'log.requests' => \App\Http\Middleware\LogRequestsMiddleware::class,
];

Apply the log.requests middleware to specific routes or groups within your application.

// Example usage in routes/web.php or routes/api.php

Route::middleware('log.requests')->get('/dashboard', function () {
    return view('dashboard');
});

You Might Also Like

Named Routes: Parameter Substitution and URL Generation

Parameter substitution in named routes and generate URLs dynamically, including handling optional pa...

Implicit and Explicit Route Model Binding

## 1. Implicit Route Model Binding ``` // Define a route with implicit model binding Route::get('us...